#include "sysloginserv.h"
#include "cgproto.pb.h"
#include <QHash>
#include <QSqlRecord>
#include "server_global.h"

SysLoginServ::SysLoginServ()
{

}

void SysLoginServ::writeDbQueryResult_b(CnsComponentPtr com, const QVariantHash& v)
{
    cgproto::LoginResponse lgRep;
    lgRep.set_status(v["status"].toString().toLatin1());
    ServerClientSocketProcPtr serverClientSocketProcPtr = com->property("serverClientSocket").value<ServerClientSocketProcPtr>();
    serverClientSocketProcPtr->msgSend(ProtoType::LOGIN_RESPONSE, lgRep);
    com->exec("loginSuccess", Q_ARG(ServerClientSocketProcPtr, serverClientSocketProcPtr));
}

void SysLoginServ::pushQueryLoginThread(CnsComponentPtr com,
             const std::string &username, const std::string &passwd)
{
    QVariantHash sv;
    sv["username"] = username.c_str();
    sv["passwd"] = passwd.c_str();
    sv["threadPath"] = "/server/.//dbQueryThread";
    REPLACEPATHLIST rpl;
    CnsComponentPtr serverClientSocket = com->property("serverClientSocket").value<CnsComponentPtr>();
    const QString *p = FRAMEWORK->getDefFullPath(com->getComDef()->getDirFullPath(), "serverClientSocket", "serverClientSocket");
    rpl << REPLACEPATH(p, serverClientSocket->getObjFullPath());
    sv["replacePathList"] = QVariant::fromValue(rpl);
    sv["sqlStringCache"] = "LoginSqlString";
    QSSHASH hash;
    hash["@user_name"] = username.c_str();
    sv["patterns"] = QVariant::fromValue(hash);
    com->exec("execTask", Q_ARG(QVariantHash&, sv));
}

void SysLoginServ::f__on_read(CnsComponentPtr com, ServerClientSocketProc* client, cgproto::Message& msg)
{
    cgproto::LoginRequest lgReq;
    if(client->server->getBaseProto().decode(msg.body().c_str(), static_cast<int>(msg.body().size()), lgReq))
    {
        pushQueryLoginThread(com, lgReq.username(), lgReq.passwd());
    }
}

void SysLoginServ::f_queryPostProcessing(CnsComponentPtr com, QVariantHash &sv, QSqlQuery &q)
{
    q.next();
    QSqlRecord && rec = q.record();
    if(rec.count()){
        sv["status"] = "login success!";
    } else{
        sv["status"] = "username or password error!";
    }
}
